package co.wangdao.xingshaoye.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import co.wangdao.xingshaoye.R;
import co.wangdao.xingshaoye.utils.LogUtil;
import co.wangdao.xingshaoye.utils.StringUtils;
import co.wangdao.xingshaoye.utils.SystemUtils;


public class NumberPicker extends LinearLayout implements OnClickListener {

    protected final String TAG = NumberPicker.class.getSimpleName();

    protected Context context;

    protected View view;

    protected int layourResId = R.layout.number_picker;

    protected int num = 0;

    protected int max = 0;

    protected int min = 1;

    protected TextView txt_num_sub, txt_num_add;
    protected EditText edit_value;

    protected int AddTure = R.drawable.productaddture2x;
    protected int AddFalse = R.drawable.productaddfalse2x;
    protected int SubTure = R.drawable.productreduceture2x;
    protected int SubFalse = R.drawable.productreducefalse2x;

    public NumberPicker setAddTure(int addTure) {
        AddTure = addTure;
        return this;
    }

    public NumberPicker setAddFalse(int addFalse) {
        AddFalse = addFalse;
        return this;
    }

    public NumberPicker setSubTure(int subTure) {
        SubTure = subTure;
        return this;
    }

    public NumberPicker setSubFalse(int subFalse) {
        SubFalse = subFalse;
        return this;
    }

    /**
     * 设置数量
     */
    public void setNum(int num) {
        // setNumAfterTextChanged(num);
        if (num > max || num < min) {
            return;
        }
        this.num = num;
        setText();
    }

    public int setNum(int num, int defalutValue) {
        if (num > max || num < min) {
            this.num = defalutValue;
            setText();
        } else {
            setNum(num);
        }
        return this.num;
    }

    // public void setNum(int num, boolean isShoppingCart) {
    // if (isShoppingCart) {
    // if (num > max || num < min) {
    // return;
    // }
    // this.num = num;
    // setText();
    // }
    // }

    protected void setNumAfterTextChanged(int num) {
        if (num > max || num < min) {
            return;
        }
        if (numberChangeListener != null)
            numberChangeListener.onChangeMax(this, num);
        this.num = num;
        if (numberChangeListener != null) {
            //LogUtil.d(TAG, "onNumberChange --- num = " + num);

            numberChangeListener.onNumberChange(this, num);
        }
        setDrawable();
    }

    /**
     * 获取当前数量
     */
    public int getNum() {
        return num;
    }

    /**
     * 显示数值
     */
    protected void setText() {
        edit_value.setText(num + "");
        setDrawable();
    }

    /**
     * 隐藏边界图片
     */
    protected boolean HideBoundary = false;

    /**
     * 设置背景
     */
    protected void setDrawable() {
        txt_num_add.setBackgroundResource(AddTure);
        txt_num_add.setEnabled(true);
        txt_num_sub.setBackgroundResource(SubTure);
        txt_num_sub.setEnabled(true);
        if (this.num == max) {
            txt_num_add.setBackgroundResource(AddFalse);
            txt_num_add.setEnabled(false);
            /** TODO 不隐藏 加号
             if (HideBoundary) {
             txt_num_add.setVisibility(GONE);
             }
             */
        } else if (this.num <= min) {
            txt_num_sub.setBackgroundResource(SubFalse);
            txt_num_sub.setEnabled(false);
            if (HideBoundary) {
                txt_num_sub.setVisibility(GONE);
                edit_value.setVisibility(GONE);
            }
        } else {
            txt_num_add.setVisibility(VISIBLE);
            txt_num_sub.setVisibility(VISIBLE);
            edit_value.setVisibility(VISIBLE);
        }
    }

    /**
     * 设置所有控件可用性
     *
     * @param isEnabled 是否可用
     */
    public void setAllEnabled(boolean isEnabled) {
        txt_num_add.setEnabled(isEnabled);
        txt_num_sub.setEnabled(isEnabled);
        edit_value.setFocusable(isEnabled);
    }

    /**
     * 设置数量的最大值
     */
    public NumberPicker setMax(int max) {
        this.max = max;
        setDrawable();
        return this;
    }

    /**
     * 获取数量的最大值
     */
    public int getMax() {
        return max;
    }

    /**
     * 设置数量的最小值
     */
    public NumberPicker setMin(int min) {
        this.min = min;
        setDrawable();
        return this;
    }

    /**
     * 获取数量的最小值
     */
    public int getMin() {
        return min;
    }

    /**
     * 设置EditText是否获得焦点
     */
    public void setFocusable(boolean focusable) {
        edit_value.setFocusable(focusable);
        edit_value.setFocusableInTouchMode(focusable);
    }

    public void setLayourResId(int layourResId) {
        this.layourResId = layourResId;
        invalidate();
    }

    public NumberPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, 60);
        setLayoutParams(params);
        setOrientation(HORIZONTAL);
        Init();
    }

    public NumberPicker setSubBackgroundResource(int resid) {
        txt_num_sub.setBackgroundResource(resid);
        return this;
    }

    public NumberPicker setSubBackgroundColor(int color) {
        txt_num_sub.setBackgroundColor(color);
        return this;
    }

    public NumberPicker setAddBackgroundResource(int resid) {
        txt_num_add.setBackgroundResource(resid);
        return this;
    }

    public NumberPicker setAddBackgroundColor(int color) {
        txt_num_add.setBackgroundColor(color);
        return this;
    }

    public NumberPicker setEditWidth(int width) {
        if (width > 0) {
            edit_value.setWidth(SystemUtils.dp2px(context, width));
        }
        return this;
    }

    public NumberPicker setEditMinWidth(int width) {
        if (width > 0) {
            edit_value.setMinWidth(SystemUtils.dp2px(context, width));
        }
        return this;
    }

    public NumberPicker setEditMaxWidth(int width) {
        if (width > 0) {
            edit_value.setMaxWidth(SystemUtils.dp2px(context, width));
        }
        return this;
    }

    public NumberPicker setEditBackgroundResource(int resid) {
        edit_value.setBackgroundResource(resid);
        return this;
    }

    public NumberPicker setEditBackgroundColor(int color) {
        edit_value.setBackgroundColor(color);
        return this;
    }

    /**
     * 设置外边距
     */
    public NumberPicker setEditMargin(int left, int top, int right, int bottom) {
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        params.setMargins(left, top, right, bottom);
        edit_value.setLayoutParams(params);
        return this;
    }

    protected void Init() {
        view = View.inflate(context, layourResId, this);
        edit_value = (EditText) view.findViewById(R.id.edit_value);
        edit_value.setPressed(true);
        txt_num_sub = (TextView) view.findViewById(R.id.txt_num_sub);
        txt_num_add = (TextView) view.findViewById(R.id.txt_num_add);

        edit_value.addTextChangedListener(new TextWatcher() {
            CharSequence text = null;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() > 0) {
                    text = s;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    LogUtil.i("------CharSequence------" + s);

                    if (StringUtils.isEmpty(s.toString())) {
                        s = "0";
                        edit_value.setText(s);
                        edit_value.setSelection(s.length());
                    }
                    if (s != null) {
                        if (s.length() >= 2) {
                            String s1 = s.toString();
                            if (s1.startsWith("0")) {
                                if (s1.charAt(1) != '0') {
                                    s = s1.substring(1);
                                } else {
                                    s = "0";
                                }
                                edit_value.setText(s);
                                edit_value.setSelection(s.length());
                            }
                        }
                    }
                    if (max >= 0 && min >= 0) {
                        int n = Integer.valueOf(s.toString());
                        if (n > max) {
                            s = String.valueOf(max);
                            edit_value.setText(s);
                            edit_value.setSelection(s.length());
                        } else if (n < min) {
                            s = String.valueOf(min);
                        }
                        return;
                    }
                } catch (Exception e) {
                    s = text;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String valueString = s.toString();
                LogUtil.d(TAG, "valueString: " + valueString);
                if (valueString != "") {
                    try {
                        setNumAfterTextChanged(Integer.parseInt(valueString));
                    } catch (Exception e) {
                    }
                }
            }
        });
        txt_num_sub.setOnClickListener(this);
        txt_num_add.setOnClickListener(this);
    }

    String t;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_num_sub:
                sub();
                break;
            case R.id.txt_num_add:
                add();
                break;
        }
    }

    protected void add() {

        int n = num + 1;
        if (n <= max) {
            if (numberChangeListener != null)
                numberChangeListener.onChangeMax(this, num);
            setNum(n);
            if (numberChangeListener != null) {
                LogUtil.d(TAG, "onAdd --- num = " + num);
                numberChangeListener.onAdd(this, num);
            }
        }
    }

    protected void sub() {
        int n = num - 1;
        if (n >= min) {
            if (numberChangeListener != null)
                numberChangeListener.onChangeMax(this, num);
            setNum(n);
            if (numberChangeListener != null) {
                LogUtil.d(TAG, "onSub --- num = " + num);
                numberChangeListener.onSub(this, num);
            }
        }
    }

    public void setOnNumberChangeListener(onNumberChangeListener l) {
        numberChangeListener = l;
    }

    onNumberChangeListener numberChangeListener;

    public interface onNumberChangeListener {
        void onAdd(NumberPicker picker, int num);

        void onSub(NumberPicker picker, int num);

        void onNumberChange(NumberPicker picker, int num);

        void onChangeMax(NumberPicker picker, int num);
    }

}
